package com.gitlab.lucky.eleme.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitlab.lucky.common.dao.model.PlatformData;
import com.gitlab.lucky.common.dao.model.WeixinGzhIntegrationRecord;
import com.gitlab.lucky.common.dao.model.WeixinGzhUser;
import com.gitlab.lucky.common.enums.CodeEnum;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.redis.RedisService;
import com.gitlab.lucky.common.weixin.WeixinUtil;
import com.gitlab.lucky.eleme.model.GroupResult;
import com.gitlab.lucky.weixin.service.WeixinGzhMsgService;
import com.gitlab.lucky.weixin.service.WeixinGzhIntegrationRecordService;
import com.gitlab.lucky.weixin.service.WeixinGzhUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Date;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-11-07 16:08
 **/
@Service
public class SyncElemService {
    public static final Logger LOGGER = LoggerFactory.getLogger(SyncElemService.class);
    @Autowired
    private WeixinGzhMsgService weixinGzhMsgService;
    @Autowired
    private ElemHandleService elemHandleService;
    @Autowired
    private WeixinGzhUserService weixinGzhUserService;
    @Autowired
    private WeixinUtil weixinUtil;
    @Autowired
    private WeixinGzhIntegrationRecordService weixinGzhIntegrationRecordService;
    @Autowired
    private RedisService redisService;

    /**
     *
     * （"该方法为异步处理"）
     * 抢红包前获取红包信息，订单号转sn，第几个最大等。
     * 调用抢红包
     * 如果返回成功扣除用户积分。
     * 如果返回失败将错误信息返回给用户。
     *
     * @param weixinGzhUser
     * @param openId
     */
    @Async
    public void syncElemQhb(WeixinGzhUser weixinGzhUser, String openId, JSONObject json, PlatformData platformData, String orderNum, String url) {
        try {
            //获取sn
            String sn = getSn(orderNum, url);
            //获取红包组信息(包含最大红包数字)
            GroupResult groupInfo = getGroupInfo(sn);
            //第几个最大
            LOGGER.info(openId,sn,groupInfo.getLucky_number(),platformData.getPlatform());
            CodeEnum result = elemHandleService.handle(openId, sn, groupInfo.getLucky_number(), platformData.getPlatform());
            //异步返回抢红包结果
            result(weixinGzhUser, openId, platformData, json, result, sn);
        } catch (Exception e) {
            LOGGER.error("error", e);
        } finally {
            weixinUtil.delSubmitCache(Constant.SUBMIT_KEY + platformData.getPlatform() + openId);
        }
    }

    public void result(WeixinGzhUser weixinGzhUser, String openId, PlatformData platformData, JSONObject json, CodeEnum result, String sn) {
        //sn组装红包url
        String url = String.format(Constant.URL, sn);
        //如果成功
        if (result.getCode() == CodeEnum.SUCCESS.getCode()) {

            WeixinGzhUser weixinGzhUsers = weixinGzhUserService.getWxUserInfoByOpenId(openId, platformData.getPlatform());
            //用户积分-10
            Integer count = weixinGzhUsers.getIntegration() - json.getInteger(Constant.MIN_COUNT);
            weixinGzhUser.setIntegration(count);
            weixinGzhUserService.updateByPrimaryKeySelective(weixinGzhUser);

            WeixinGzhIntegrationRecord weixinGzhIntegrationRecord = new WeixinGzhIntegrationRecord();
            weixinGzhIntegrationRecord.setCreateTime(new Date());
            weixinGzhIntegrationRecord.setPlatform(platformData.getPlatform());
            weixinGzhIntegrationRecord.setType(CodeEnum.LUCKY.getCode());
            weixinGzhIntegrationRecord.setOpenId(openId);
            weixinGzhIntegrationRecord.setIntegration("-"+json.getInteger(Constant.MIN_COUNT));
            weixinGzhIntegrationRecord.setIntegrationBalance(count);
            weixinGzhIntegrationRecordService.insertSelective(weixinGzhIntegrationRecord);

            //用户剩余积分
            String select_count = String.format(json.getString(Constant.SELECT_COUNT),json.getInteger(Constant.MIN_COUNT), count);
            //返回给用户
            weixinGzhMsgService.resultServerNews(openId, json.getString(Constant.HB_SUCCESS), select_count, url, platformData.getAvatar(), platformData.getPlatform());
            LOGGER.info("抢红包成功---手机号:{}---平台:{}", weixinGzhUser.getPhone(), platformData.getPlatform());
        } else {
            //返回错误信息
            weixinGzhMsgService.resultServerNews(openId, Constant.LUCKY_FAIL, result.getMsg(), url, platformData.getAvatar(), platformData.getPlatform());
        }
    }

    /**
     * 组信息,从中获取第几个是最大
     *
     * @param groupSn
     * @return
     */
    public GroupResult getGroupInfo(String groupSn) {
        String url = String.format(Constant.GET_GROUP_URL, groupSn);
        HttpRequest get = HttpUtil.createGet(url).timeout(3000);
        String result = get.execute().body();
        GroupResult groupResult = JSONObject.parseObject(result, GroupResult.class);
        return groupResult;
    }

    /**
     * 通过订单号或红包链接获取sn
     *
     * @param orderNum
     * @param url
     * @return
     */
    public String getSn(String orderNum, String url) {
        String sn = "";
        if (StringUtils.isNotBlank(orderNum)) {
            sn = Long.toHexString(Long.parseLong(orderNum));
        }
        if (StringUtils.isNotBlank(url) && url.contains("sn=")) {
            String[] split = url.split("sn=");
            if (split[1].contains("&")) {
                String[] split1 = split[1].split("&");
                return split1[0];
            }
            sn = split[1];
        }
        return sn;
    }
}
